package com.haojiangbo.config.result;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 *  处理返回结果
 *  @author 郝江波
 *  @date 2021/2/8 10:18
 *
 */
public class ServiceMagicResultHander implements HandlerMethodReturnValueHandler {

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        Service service = returnType.getDeclaringClass().getAnnotation(Service.class);
        return service == null ? false : true;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        response.setCharacterEncoding("utf-8");
        if (returnValue instanceof Comparable) {
            response.getWriter().write(returnValue.toString());
            response.getWriter().flush();
        } else if (response instanceof List) {
            setJsonContent(response);
            response.getWriter().write(JSONArray.toJSONString(returnValue));
        } else {
            setJsonContent(response);
            response.getWriter().write(JSONObject.toJSONString(returnValue));
        }
        response.getWriter().flush();
        mavContainer.setRequestHandled(true);
    }

    private void setJsonContent(HttpServletResponse response) {
        response.setContentType("application/json; charset=utf-8");
    }
}
